package com.woniuxy.purchasemanager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.entity.sale.dto.SoAccountDto;
import com.woniuxy.commons.entity.sale.vo.sale.SoAccountVo;
import com.woniuxy.commons.result.Result;
import com.woniuxy.commons.service.sale.SaleService;
import com.woniuxy.purchasemanager.service.AbsFileExportServiceAdapter;
import com.woniuxy.purchasemanager.service.SoAccountFileService;
import com.woniuxy.purchasemanager.util.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 打印订单信息
 * <P> Date: 2022/4/25:15:23
 * <P> Description:
 */
@Service
public class SoAccountFileServiceImpl implements SoAccountFileService {

    private final static Logger LOGGER = LoggerFactory.getLogger(NeedAllocationFileServiceImpl.class);

    /**
     * TODO 获取单元格样式
     */
    HorizontalCellStyleStrategy cellStyleStrategy = ExcelUtils.getHorizontalCellStyleStrategy();

    private static final String filename = "分配需求单导出数据表";


    @Resource
    private SaleService saleService;


     public List getNeedAllocationData(Integer current,
                                       Integer limit,
                                       SoAccountVo soAccountVo) {
         //查询数据

         Result soAccountAll = saleService.findSoAccountAll(current,limit,soAccountVo);
         LinkedHashMap linkedHashMap = (LinkedHashMap) soAccountAll.getData();

         ObjectMapper objectMapper = new ObjectMapper();

         List list = (List) linkedHashMap.get("list");

         ArrayList<Object> objects = new ArrayList<>();
         list.forEach(list1 -> {
             SoAccountDto soAccountDto =
                     objectMapper.convertValue(list1, SoAccountDto.class);
             objects.add(soAccountDto);
         });


         return objects;
     }


    @Override
    public ExcelWriter findChooseProduceBySoIdAsExce(HttpServletResponse response, Integer currentPage, Integer limit, SoAccountVo soAccountVo) {

        // 使用接口适配器实现方法
        AbsFileExportServiceAdapter afes = new AbsFileExportServiceAdapter() {
            @Override
            public void exportDataToExcel(HttpServletResponse response) {
                ExcelWriter excelWriter = null;
                try {
                    response.setContentType("application/vnd.ms-excel");
                    response.setCharacterEncoding("utf-8");
                    //这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
                    String fileName = URLEncoder.encode(filename + "-" + System.currentTimeMillis(), "UTF-8")
                            .replaceAll("\\+", "%20");
                    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
                    // 这里 需要指定写用哪个class去写
                    excelWriter = EasyExcel.write(response.getOutputStream(), SoAccountDto.class).build();
                    // 这里注意 如果同一个sheet只要创建一次
                    WriteSheet writeSheet = EasyExcel.writerSheet("").registerWriteHandler(cellStyleStrategy).build();
                    // 去调用写入,实际使用时根据数据库分页的总的页数来
                    writeSheet.setSheetName("sheet" + 1);
                    // 去数据库查询每一页的数据
                    ExcelWriter write = excelWriter.write(getNeedAllocationData(currentPage,limit,soAccountVo), writeSheet);
                    LOGGER.info("数据导出完成");
                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.error("导出数据失败！错误信息为：{}", e.getMessage());
                } finally {
                    //千万别忘了finish,会帮我们自动关闭流
                    if (excelWriter != null) {
                        excelWriter.finish();
                    }
                }
            }
        };

        afes.exportDataToExcel(response);
        return null;
    }
}
